package com.luo.ai.assistant.util;

import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.net.http.HttpClient;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

public class RestClientUtil {

    public static RestTemplate createRestTemplateWithDisabledSSLVerification() {
            HttpClient httpClient = createHttpClientWithDisabledSSLVerification();
            JdkClientHttpRequestFactory jdkClientHttpRequestFactory = new JdkClientHttpRequestFactory();
            // Create a RestTemplate with the custom request factory
            return new RestTemplate(jdkClientHttpRequestFactory);
    }

    public static HttpClient createHttpClientWithDisabledSSLVerification() {
        try {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
                        @Override
                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }
                        @Override
                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        }
                    }
            };

            // Install the all-trusting trust manager
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            // Create an HttpClient with the custom SSLContext
            return HttpClient.newBuilder()
                    .sslContext(sslContext)
                    .build();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new RuntimeException("Failed to create a HTTP client with disabled SSL verification", e);
        }
    }

    public static RestClient.Builder createRestClientBuilderWithDisabledSSLVerification() {
        RestTemplate restTemplate = createRestTemplateWithDisabledSSLVerification();
        return RestClient.builder(restTemplate);
    }

}